package com.gcsj.controller;

import com.alibaba.fastjson.JSONObject;
import com.gcsj.pojo.User;
import com.gcsj.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
public class UploadController {

    @Autowired
    private UserService userService;

    //上传图片
    @PostMapping("/avatar")
    public JSONObject upload(@RequestParam MultipartFile file, @RequestParam Integer id){
        JSONObject jsonObject = new JSONObject();
        if(null == file) {
            jsonObject.put("code", 201);
            jsonObject.put("msg", "上传图片为空");
            return jsonObject;
        }
        //默认
        String type = "images\\avatar\\";
        String  realPath = System.getProperty("user.dir") + "\\src\\main\\resources\\static\\" + type;
        File dir = new File(realPath);
        if (!dir.isDirectory()){
            dir.mkdirs();
        }

        String oldName = file.getOriginalFilename();
//        System.out.println(oldName);
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.indexOf("."), oldName.length());

        try {
            file.transferTo(new File(realPath + "/" + newName));
//            System.out.println(new File(realPath + "/" + newName));

            User userById = userService.getUserById(id);

            if(null != userById) {

//                System.out.println(newName);
//                System.out.println(userById);
//                System.out.println("1111");

                userById.setAvatar("avatar/" + newName);
                int i = 0;
                i = userService.updateAvatar(userById);
//                System.out.println(i);
                if(i == 1) {
                    jsonObject.put("code", 200);
                    jsonObject.put("msg", "上传图片成功!");
                    return jsonObject;
                }
            }


        } catch (IOException e) {
            jsonObject.put("code", 201);
            jsonObject.put("msg", e);
            return jsonObject;
        }
        jsonObject.put("code", 201);
        jsonObject.put("msg", "其他错误");
        return jsonObject;
    }
}
